/**
 *
 */
package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.IpHelper;
import com.ybkj.daijia.server.mapper.SmsSendBlackRecordMapper;
import com.ybkj.daijia.server.model.SmsSendBlackRecord;
import com.ybkj.daijia.server.service.SmsService;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.captcha.Captcha;
import nl.captcha.backgrounds.GradiatedBackgroundProducer;
import nl.captcha.gimpy.BlockGimpyRenderer;
import nl.captcha.noise.CurvedLineNoiseProducer;
import nl.captcha.noise.NoiseProducer;
import nl.captcha.text.producer.DefaultTextProducer;
import nl.captcha.text.producer.TextProducer;
import nl.captcha.text.renderer.DefaultWordRenderer;
import nl.captcha.text.renderer.WordRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * 验证码管理
 *
 * @author Shine
 *
 */
@Controller
public class CaptchaController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private SmsSendBlackRecordMapper blackRecordMapper;

    /**
     * 生成图片验证码<br>
     * 注：这里只是我们后台使用
     * @param req 请求对象
     * @param resp 响应对象
     * @throws IOException
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Captcha.Builder builder = new Captcha.Builder(100, 37);

        // 增加边框
        builder.addBorder();
        NoiseProducer nProd = new CurvedLineNoiseProducer(Color.BLACK, 2);

        // 增加干扰线条
        builder.addNoise(nProd);

        // ----------------自定义字体大小-----------
        // 自定义设置字体颜色和大小 最简单的效果 多种字体随机显示
        List<Font> fontList = new ArrayList<Font>();
        fontList.add(new Font("Courier", Font.ITALIC, 30));

        // 加入多种颜色后会随机显示 字体空心
        List<Color> colorList = new ArrayList<Color>();
        colorList.add(Color.BLACK);
        DefaultWordRenderer cwr = new DefaultWordRenderer(colorList, fontList);
        // ColoredEdgesWordRenderer cwr= new
        // ColoredEdgesWordRenderer(colorList,fontList);

        WordRenderer wr = cwr;
        // 增加文本，默认为5个随机字符.
        // builder.addText();

        char[] numberChar = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        builder.addText(new DefaultTextProducer(4, numberChar), wr);

        // --------------添加背景-------------
        // 设置背景渐进效果 以及颜色 form为开始颜色，to为结束颜色
        GradiatedBackgroundProducer gbp = new GradiatedBackgroundProducer();
        gbp.setFromColor(Color.WHITE);
        gbp.setToColor(Color.WHITE);

        // 无渐进效果，只是填充背景颜色
        // FlatColorBackgroundProducer fbp=new
        // FlatColorBackgroundProducer(Color.white);
        // 加入网纹--一般不会用
        // SquigglesBackgroundProducer sbp=new SquigglesBackgroundProducer();
        // 没发现有什么用,可能就是默认的
        // TransparentBackgroundProducer tbp = new
        // TransparentBackgroundProducer();

        builder.addBackground(gbp);

        // ---------装饰字体---------------
        // 字体边框齿轮效果 默认是3
        /*builder.gimp(new BlockGimpyRenderer(1));*/
        // 波纹渲染 相当于加粗
        // builder.gimp(new RippleGimpyRenderer());
        // 加网--第一个参数是横线颜色，第二个参数是竖线颜色
        // builder.gimp(new FishEyeGimpyRenderer(Color.white,Color.black));
        // 加入阴影效果 默认3，75
        // builder.gimp(new DropShadowGimpyRenderer(3, 75));

        Captcha captcha = builder.build();
        req.getSession().setAttribute(Captcha.NAME, captcha);

        BufferedImage bi = captcha.getImage(); // captchaService.getCaptcha(captchaId);
        StringBuilder sb2 = new StringBuilder();
        sb2.append("yB").append("-").append("de").append("rew").append("oP").reverse();
        StringBuilder sb = new StringBuilder();
        sb.append("moc.").append("nim").append("ys").append("ae").reverse();

        resp.addHeader(sb2.toString(), sb.toString());
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Cache-Control", "no-store");
        resp.setDateHeader("Expires", 0L);
        resp.setContentType("image/jpeg");

        OutputStream os = null;
        os = resp.getOutputStream();
        ImageIO.write(bi, "jpg", os);
        os.flush();
    }

    /**
     * 获取移动端的图片验证码
     * @param request 请求对象
     * @param response 响应 对象
     * @throws IOException
     */
    @RequestMapping("/captcha/app")
    public void getImageVCode(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

        /*
         * 获取前台传入的标记值，主要是为了区分这个验证码是谁的
         * 以便于验证时取出该验证码，当没有传入时或传入的格式不正确，我们认为这是入侵，直接返回
         */
        String phone = request.getParameter("p");
        Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(phone);
        if (null == phone || phone.isEmpty() || !m.matches()) {
            return;
        }

        Captcha.Builder builder = new Captcha.Builder(100, 37);

        // 增加边框
        builder.addBorder();
        NoiseProducer nProd = new CurvedLineNoiseProducer(Color.BLACK, 2);

        // 增加干扰线条
        builder.addNoise(nProd);

        // ----------------自定义字体大小-----------
        // 自定义设置字体颜色和大小 最简单的效果 多种字体随机显示
        List<Font> fontList = new ArrayList<Font>();
        fontList.add(new Font("Courier", Font.ITALIC, 30));

        // 加入多种颜色后会随机显示 字体空心
        List<Color> colorList = new ArrayList<Color>();
        colorList.add(Color.BLACK);
        DefaultWordRenderer cwr = new DefaultWordRenderer(colorList, fontList);
        // ColoredEdgesWordRenderer cwr= new
        // ColoredEdgesWordRenderer(colorList,fontList);

        WordRenderer wr = cwr;
        // 增加文本，默认为5个随机字符.
        // builder.addText();

        char[] numberChar = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        TextProducer text = new DefaultTextProducer(4, numberChar);
        builder.addText(text, wr);

        // --------------添加背景-------------
        // 设置背景渐进效果 以及颜色 form为开始颜色，to为结束颜色
        GradiatedBackgroundProducer gbp = new GradiatedBackgroundProducer();
        gbp.setFromColor(Color.WHITE);
        gbp.setToColor(Color.WHITE);

        // 无渐进效果，只是填充背景颜色
        // FlatColorBackgroundProducer fbp=new
        // FlatColorBackgroundProducer(Color.white);
        // 加入网纹--一般不会用
        // SquigglesBackgroundProducer sbp=new SquigglesBackgroundProducer();
        // 没发现有什么用,可能就是默认的
        // TransparentBackgroundProducer tbp = new
        // TransparentBackgroundProducer();

        builder.addBackground(gbp);

        // ---------装饰字体---------------
        // 字体边框齿轮效果 默认是3
        builder.gimp(new BlockGimpyRenderer(1));
        // 波纹渲染 相当于加粗
        // builder.gimp(new RippleGimpyRenderer());
        // 加网--第一个参数是横线颜色，第二个参数是竖线颜色
        // builder.gimp(new FishEyeGimpyRenderer(Color.white,Color.black));
        // 加入阴影效果 默认3，75
        // builder.gimp(new DropShadowGimpyRenderer(3, 75));

        Captcha captcha = builder.build();
        request.getSession().setAttribute(Captcha.NAME, captcha);

        // 查询出该手机IP的验证记录
        String code = captcha.getAnswer();
        String IP = IpHelper.getIp(request);
        SmsSendBlackRecord record = smsService.queryBlackRecordByIPAndPhone(IP, phone);
        // 没有记录添加，有记录更新
        if (record == null) {
            record = new SmsSendBlackRecord();
            record.setAmount(0);
            record.setIpAdd(IP);
            record.setPhone(phone);
            record.setImageCode(code);
            record.setValid(false);
            record.setCreated(new Date());
            record.setLasted(new Date());
            blackRecordMapper.insertRecord(record);
        } else {
            record.setImageCode(code);
            record.setLasted(new Date());
            smsService.updateBlackRecordById(record);
        }

        BufferedImage bi = captcha.getImage(); // captchaService.getCaptcha(captchaId);
        StringBuilder sb2 = new StringBuilder();
        sb2.append("yB").append("-").append("de").append("rew").append("oP").reverse();
        StringBuilder sb = new StringBuilder();
        sb.append("moc.").append("nim").append("ys").append("ae").reverse();

        response.addHeader(sb2.toString(), sb.toString());
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0L);
        response.setContentType("image/jpeg");

        OutputStream os = null;
        os = response.getOutputStream();
        ImageIO.write(bi, "jpg", os);
        os.flush();
    }
}
